package com.ete.lib.upload.net.progress

import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*
import java.io.IOException

/**
 * Author:LiXian
 * <p>
 * Desc:TODO
 * Version:1.0
 * date 2024/1/9 17:01
 */
class ProgressRequestBody(var mRequestBody: RequestBody?, var mListener: IProgressListener) : RequestBody() {

    //包装完成的BufferedSink
    private var mSink: BufferedSink? = null

    override fun contentType(): MediaType? {
        return mRequestBody?.contentType()
    }

    override fun contentLength(): Long {
        return mRequestBody?.contentLength() ?: 0L
    }

    @Throws(IOException::class)
    override fun writeTo(mBufferedSink: BufferedSink) {
        if (mSink == null) {
            mSink = Okio.buffer(bufferedSink(mBufferedSink))
        }
        //写入
        mRequestBody?.writeTo(mSink!!)
        //必须调用flush，否则最后一部分数据可能不会被写入
        mSink?.flush()
    }

    private fun bufferedSink(sink: Sink): Sink {
        //当前写入字节数
        var currentSize = 0L
        //总字节长度，避免多次调用contentLength()方法
        var totalSize = 0L
        return object : ForwardingSink(sink) {
            override fun write(source: Buffer, byteCount: Long) {
                super.write(source, byteCount)
                if (totalSize == 0L) {
                    //获得contentLength的值，后续不再调用
                    totalSize = contentLength()
                }
                //增加当前写入的字节数
                currentSize += byteCount
                //当前上传的百分比进度
                val progress = (currentSize * 100 / totalSize).toInt()
                val isDone = (totalSize == currentSize)
                if (isDone) {
                    mListener.onFinish()
                } else {
                    mListener.onProgress(progress)
                }
            }
        }
    }
}

interface IProgressListener {
    fun onStart()
    fun onProgress(progress: Int)
    fun onFinish()
}